package com.javastudy.autowiredStudy.configurationPropertiesStudy;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.Set;

/**
 * Apollo注册中心会存在复杂的参数配置无法自动更新的问题
 *  使用监听器解决
 * @author mac
 * @date 2021/9/9 1:46 下午
 */
@ConditionalOnClass(EnableApolloConfig.class)//如果开启了Apollo注册中心的配置那么就会走这段代码
//解决跨域问题适合接口很少的情况
@CrossOrigin(origins = "http://localhost:8016")
public class ApolloConfigurationAutoRefresh implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Transactional(propagation = Propagation.NEVER)
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 配置Apollo注册中心的监听器
     * @param event
     */
    @ApolloConfigChangeListener
    private void onChange(ConfigChangeEvent event){
        refreshConfig(event.changedKeys());
    }

    /**
     * 将复杂对象写到对应的配置对象当中的逻辑
     * @param changeKeys
     */
    private void refreshConfig(Set<String> changeKeys){
        System.out.println("将复杂对象写到对应的配置对象当中的逻辑");
    }
}
